<?php

class Application_Model_Registration {

	public function login($name, $password){
		$result = new Application_Model_Result();
		$name = trim($name);
		$password = trim($password);		
		$dbUser = new Application_Model_DbTable_Users();
		$user = $dbUser->checkUser($name,$password);
		if($user){
			session_start();
			$_SESSION["user"] = $user->toArray();
			$result->success = true;
		}else{
			$result->success = false;
			$result->message = "Login failed!";			
		}
		return $result;		
	}
	
	public function register($name,$password,$email){
		$result = new Application_Model_Result();
		$name = trim($name);
		$password = trim($password);
		$email = trim($email);
		$dbUser = new Application_Model_DbTable_Users();
		$row = $dbUser->checkUserName($name);			
		$user = $dbUser->createUser($name,$password,$email,0,"");
		if($row != null) {
			$result->success = false;
			$result->message = "duplicated user name!";
		} else {
			session_start();
			$_SESSION["user"] = $user->toArray();
			$result->success = true;
		}
		echo json_encode($result);
	}
	
	public function updateUser($id,$name,$password,$email,$location,$address){
		$result = new Application_Model_Result();
		$name = trim($name);
		$dbUser = new Application_Model_DbTable_Users();
		$rows = $dbUser->checkUserName($name);
		$u = $rows->toArray();
		if($rows != null && $u["id"] != $id) {
			$result->success = false;
			$result->message = "duplicated user name!";
			echo json_encode($result);
			return;					
		}
		$password = trim($password);
		$email = trim($email);
		$location = trim($location);
		$address = trim($address);
		$dbUser = new Application_Model_DbTable_Users();
		$user = $dbUser->updateUser($id,$name,$password,$email,$location,$address);
		$result->success = true;
		echo json_encode($result);
	}
	
	public function getUser($id){
		$data = new Application_Model_Dataobject();
		$result = new Application_Model_Result();
		$dbUser = new Application_Model_DbTable_Users();
		$user = $dbUser->getUser($id);
		$u = $user->toArray();
		$result->success = true;
		$data->data = $u;
		$data->result = $result;
		echo json_encode($data);
	}
}

